package cn.edu.lingnan.controller;

import cn.edu.lingnan.entity.dto.ProductDto;
import cn.edu.lingnan.entity.pojo.Product;
import cn.edu.lingnan.service.ProductService;
import cn.edu.lingnan.entity.pojo.Result;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/v1/products")
@Slf4j
public class ProductController {

    @Autowired
    private ProductService productService;

    /**
     * 获取分页的商品列表
     *
     * @param productDto 包含分页和筛选条件的DTO
     * @return 分页结果
     */
    @PostMapping("/list")
    public Result<Page<Product>> getProducts(@RequestBody ProductDto productDto) {
        Page<Product> resultPage = productService.getProductsByPage(productDto);
         log.info("分页查询商品列表，条件：{}, ", productDto);
        return Result.success(resultPage);
    }
    /**
     * 添加新商品
     *
     * @param product 商品信息
     * @return 操作结果
     */
    @PostMapping("/add")
    public Result<String> addProduct(@RequestBody Product product,@RequestParam("point") Integer point) {
        boolean save = productService.saveProduct(product,point);
        return save ? Result.success("商品添加成功") : Result.error("商品添加失败");
    }

    /**
     * 更新商品信息
     *
     * @param product 商品信息
     * @return 操作结果
     */
    @PutMapping("/update")
    public Result<String> updateProduct(@RequestBody Product product) {
        boolean update = productService.updateById(product);
        return update ? Result.success("商品更新成功") : Result.error("商品更新失败");
    }

    /**
     * 删除商品
     *
     * @param productId 商品ID
     * @return 操作结果
     */
    @DeleteMapping("/delete/{id}")
    public Result<String> deleteProduct(@PathVariable("id") Integer productId) {
        boolean remove = productService.removeById(productId);
        return remove ? Result.success("商品删除成功") : Result.error("商品删除失败");
    }

    /**
     * 根据商品ID查询商品详情
     *
     * @param productId 商品ID
     * @return 商品详情
     */
    @GetMapping("/{id}")
    public Result<Product> getProductById(@PathVariable("id") Integer productId) {
        Product product = productService.getById(productId);
        if (product != null) {
            return Result.success(product);
        } else {
            return Result.error("商品未找到");
        }
    }
}
